﻿using AutoMapper;
using BJoin.DemoProject.Repository;
using BJoin.DemoProject.Manager;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;
using System.Linq.Expressions;
using BJoin.DemoProject.Entities;
using BJoin.DapperExtension.Linq;
using System.Collections.Generic;
using BJoin.DemoProject.ExtObject;
using DapperExtensions;
using BJoin.DapperExtension.DatabaseFactory;
using Microsoft.Extensions.Logging;

namespace BJoin.DemoProject.Service
{
    public class FileService:FileManager,IFileService
    {
        public FileService(ILogger<FileService> logger,IConfiguration configuration,IFileManager manager,IServiceProvider provider, IFileRepository repository, IMapper mapper, IDbFactory<IDatabase, long?> factory) :base(logger,configuration,provider,repository,mapper,factory)
        {
        }

        public async Task<long> HelloExpression(string code, string name)
        {
            Expression<Func<FileEntity, bool>> expression = f => f.Code == "code5" && f.Name == (name!=null?name:(string)null);
            #region expression in service/manager
            return await base.CountAsync(expression);
            #endregion 
            #region expression in Repository
            //var predicate = Expression2Predicate<FileEntity>.FromExpression(expression);
            //return await Repository.CountAsync(predicate);
            #endregion
        }

        /// <summary>
        /// 批量添加（事务）
        /// </summary>
        /// <typeparam name="TAddDto"></typeparam>
        /// <param name="addDtos"></param>
        /// <returns></returns>
        public override async Task<IEnumerable<long>> AddManyAsync<TAddDto>(IEnumerable<TAddDto> addDtos)
        {
            //transcation support
            IEnumerable<long> ids = new List<long>();
            await WriteAsync(async database=> await database.RunInTransactionAsync( async () =>
            {
                var entities = await AddDto2EntityAsync(addDtos);
                ids = await Repository.InsertManyAsync(database, entities);
            }));
            return ids;
        }
    }
}
